package in.co.codedoc.sql;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.Set;

public class DeleteStatement
	extends SQLStatement
{
	public DeleteStatement()
	{
		where = new WhereClause(this);
	}

	@Override
	public PrintWriter Generate(PrintWriter out) throws IOException
	{
		out.write("DELETE FROM ");

		Set<Table> tables = where.GetTables();
		
		if(tables.isEmpty())
		{
			if(fromTable == null)
			{
				throw new RuntimeException
				(
					"It is not recommended to do 'delete from foo;' from a program." +
					" But since you want to attempt it, try invoking From(Table)" +
					" method on thsi object before invoking ExecuteUpdate."
				);
			}
			
			out.write(fromTable.GetTableName());
		}
		else
		{
			out.write(tables.iterator().next().GetTableName());
		}
		
		if(!where.IsEmpty())
		{
			out.write(" WHERE ");
			where.Generate(out);
		}
		
		return out;
	}

	@Override
	public void GetParameterValues(LinkedList<DBInputColumnMap> values)
	{
		where.GetParameterValues(values);
	}

	public WhereClause Where()
	{
		return where;
	}
	
	public DeleteStatement From(Table table)
	{
		this.fromTable = table;
		return this;
	}

	private Table fromTable;
	private WhereClause where;
}
